<template>
  <div class="app-container">
    <!-- 顶部导航栏 -->
    <header class="header">
      <div class="logo">
        <el-icon><Trophy /></el-icon>
        运动会管理系统
      </div>
      <div class="flex-grow"></div>
      <div class="flex items-center gap-6">
        <div class="flex items-center gap-2">
          <el-avatar :size="40" :src="currentUser?.avatar || 'img/jstu1.webp'">
            {{ currentUser?.realName?.charAt(0) || '管' }}
          </el-avatar>
          <span class="text-white text-sm">{{ currentUser?.realName || '管理员' }}</span>
        </div>
        <div class="flex items-center gap-2">
          <el-button type="text" @click="handleLogout" style="color: white;">
            <el-icon><SwitchButton /></el-icon>退出登录
          </el-button>
        </div>
      </div>
    </header>

    <!-- 左侧导航栏 -->
    <nav class="sidebar">
      <div class="menu-item" :class="{ active: $route.path === '/admin' }" @click="$router.push('/admin')">
        <el-icon><Odometer /></el-icon>
        <span>系统管理</span>
      </div>
      <div class="menu-item" @click="$router.push('/admin/users')">
        <el-icon><User /></el-icon>
        <span>用户管理</span>
      </div>
      <div class="menu-item" @click="$router.push('/admin/projects')">
        <el-icon><List /></el-icon>
        <span>项目管理</span>
      </div>
      <div class="menu-item" @click="$router.push('/admin/schedule')">
        <el-icon><Clock /></el-icon>
        <span>赛程管理</span>
      </div>
      <div class="menu-item active">
        <el-icon><Trophy /></el-icon>
        <span>成绩管理</span>
      </div>
    </nav>

    <!-- 主要内容 -->
    <main class="content">
      <!-- 面包屑导航 -->
      <div class="breadcrumb">
        <el-breadcrumb separator="/">
          <el-breadcrumb-item :to="{ path: '/admin' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>成绩管理</el-breadcrumb-item>
          <el-breadcrumb-item>成绩公示</el-breadcrumb-item>
        </el-breadcrumb>
      </div>

      <!-- 页面标题 -->
      <div class="main-content-header">
        <h1 class="text-2xl font-medium">成绩公示</h1>
        <div class="header-actions">
          <el-button-group>
            <el-button type="primary" size="small" @click="handleRefresh" :loading="refreshing">
              <el-icon><Refresh /></el-icon> 刷新数据
            </el-button>
            <el-button type="success" size="small" @click="handleExport">
              <el-icon><Download /></el-icon> 导出成绩
            </el-button>
            <el-button type="warning" size="small" @click="handlePrint">
              <el-icon><Printer /></el-icon> 打印成绩
            </el-button>
          </el-button-group>
        </div>
      </div>

      <!-- 统计信息卡片 -->
      <div class="statistics-cards">
        <el-row :gutter="20">
          <el-col :xs="12" :sm="6" v-for="(stat, key) in statisticsCards" :key="key">
            <el-card class="stat-card" shadow="hover">
              <div class="stat-content">
                <div class="stat-icon" :class="key">
                  <el-icon><component :is="stat.icon" /></el-icon>
                </div>
                <div class="stat-info">
                  <div class="stat-value">{{ stat.value }}</div>
                  <div class="stat-label">{{ stat.label }}</div>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 奖牌统计 -->
      <div class="medal-statistics">
        <el-card class="medal-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>奖牌统计</span>
              <el-select v-model="selectedProject" placeholder="选择项目" size="small" style="width: 200px" @change="handleProjectChange">
                <el-option label="全部项目" :value="null"></el-option>
                <el-option
                  v-for="project in projectOptions"
                  :key="project.id"
                  :label="project.name"
                  :value="project.id">
                </el-option>
              </el-select>
            </div>
          </template>
          <div class="medal-content">
            <div class="medal-item gold" @click="handleMedalClick('gold')">
              <div class="medal-icon">
                <el-icon><Medal /></el-icon>
              </div>
              <div class="medal-info">
                <div class="medal-count">{{ medalStatistics.gold }}</div>
                <div class="medal-label">金牌</div>
              </div>
            </div>
            <div class="medal-item silver" @click="handleMedalClick('silver')">
              <div class="medal-icon">
                <el-icon><Medal /></el-icon>
              </div>
              <div class="medal-info">
                <div class="medal-count">{{ medalStatistics.silver }}</div>
                <div class="medal-label">银牌</div>
              </div>
            </div>
            <div class="medal-item bronze" @click="handleMedalClick('bronze')">
              <div class="medal-icon">
                <el-icon><Medal /></el-icon>
              </div>
              <div class="medal-info">
                <div class="medal-count">{{ medalStatistics.bronze }}</div>
                <div class="medal-label">铜牌</div>
              </div>
            </div>
          </div>
        </el-card>
      </div>

      <!-- 数据可视化图表 -->
      <div class="charts-section">
        <el-row :gutter="20">
          <el-col :xs="24" :lg="12">
            <el-card class="chart-card" shadow="hover">
              <template #header>
                <div class="card-header">
                  <span>院系成绩分布</span>
                  <el-button-group size="small">
                    <el-button :type="chartType === 'bar' ? 'primary' : ''" @click="chartType = 'bar'">柱状图</el-button>
                    <el-button :type="chartType === 'pie' ? 'primary' : ''" @click="chartType = 'pie'">饼图</el-button>
                  </el-button-group>
                </div>
              </template>
              <div ref="departmentChartRef" class="chart-container"></div>
            </el-card>
          </el-col>
          <el-col :xs="24" :lg="12">
            <el-card class="chart-card" shadow="hover">
              <template #header>
                <div class="card-header">
                  <span>项目成绩趋势</span>
                  <el-select v-model="chartProjectId" placeholder="选择项目" size="small" style="width: 150px" @change="updateProjectChart">
                    <el-option
                      v-for="project in projectOptions.slice(0, 5)"
                      :key="project.id"
                      :label="project.name"
                      :value="project.id">
                    </el-option>
                  </el-select>
                </div>
              </template>
              <div ref="projectChartRef" class="chart-container"></div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 主要内容区域 -->
      <div class="main-content">
        <!-- 左侧搜索和筛选 -->
        <div class="left-panel">
          <el-card class="search-card" shadow="hover">
            <template #header>
              <div class="card-header">
                <span>成绩查询</span>
                <el-button type="text" @click="handleResetSearch">重置</el-button>
              </div>
            </template>

            <el-form :model="searchForm" label-width="80px" size="small">
              <el-form-item label="项目">
                <el-select v-model="searchForm.projectId" placeholder="请选择项目" clearable style="width: 100%">
                  <el-option
                    v-for="project in projectOptions"
                    :key="project.id"
                    :label="project.name"
                    :value="project.id">
                  </el-option>
                </el-select>
              </el-form-item>

              <el-form-item label="学生">
                <el-input v-model="searchForm.studentName" placeholder="请输入学生姓名" clearable>
                  <template #prefix>
                    <el-icon><Search /></el-icon>
                  </template>
                </el-input>
              </el-form-item>

              <el-form-item label="学号">
                <el-input v-model="searchForm.studentNumber" placeholder="请输入学号" clearable>
                  <template #prefix>
                    <el-icon><User /></el-icon>
                  </template>
                </el-input>
              </el-form-item>

              <el-form-item label="学院">
                <el-select v-model="searchForm.department" placeholder="请选择学院" clearable style="width: 100%">
                  <el-option
                    v-for="dept in departmentOptions"
                    :key="dept"
                    :label="dept"
                    :value="dept">
                  </el-option>
                </el-select>
              </el-form-item>

              <el-form-item label="状态">
                <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 100%">
                  <el-option
                    v-for="status in statusOptions"
                    :key="status.value"
                    :label="status.label"
                    :value="status.value">
                  </el-option>
                </el-select>
              </el-form-item>

              <el-form-item label="轮次">
                <el-select v-model="searchForm.round" placeholder="请选择轮次" clearable style="width: 100%">
                  <el-option
                    v-for="round in roundOptions"
                    :key="round.value"
                    :label="round.label"
                    :value="round.value">
                  </el-option>
                </el-select>
              </el-form-item>

              <el-form-item label="破纪录">
                <el-switch v-model="searchForm.isRecord" />
              </el-form-item>

              <el-form-item>
                <el-button type="primary" @click="handleSearch" :loading="searchLoading" style="width: 100%">
                  <el-icon><Search /></el-icon> 搜索
                </el-button>
              </el-form-item>
            </el-form>
          </el-card>

          <!-- 个人成绩查询 -->
          <el-card class="personal-card" shadow="hover">
            <template #header>
              <div class="card-header">
                <span>个人成绩查询</span>
              </div>
            </template>

            <el-form :model="personalForm" label-width="80px" size="small">
              <el-form-item label="学生姓名">
                <el-input v-model="personalForm.studentName" placeholder="请输入学生姓名">
                  <template #prefix>
                    <el-icon><User /></el-icon>
                  </template>
                </el-input>
              </el-form-item>

              <el-form-item label="学号">
                <el-input v-model="personalForm.studentNumber" placeholder="请输入学号">
                  <template #prefix>
                    <el-icon><CreditCard /></el-icon>
                  </template>
                </el-input>
              </el-form-item>

              <el-form-item>
                <el-button type="primary" @click="handlePersonalSearch" :loading="personalLoading" style="width: 100%">
                  <el-icon><Search /></el-icon> 查询
                </el-button>
              </el-form-item>
            </el-form>
          </el-card>
        </div>

        <!-- 右侧成绩列表 -->
        <div class="right-panel">
          <el-card class="table-card" shadow="hover">
            <template #header>
              <div class="card-header">
                <div class="header-left">
                  <span>成绩列表</span>
                  <el-radio-group v-model="displayMode" size="small" class="display-mode-group">
                    <el-radio-button label="table">表格视图</el-radio-button>
                    <el-radio-button label="card">卡片视图</el-radio-button>
                    <el-radio-button label="ranking">排行榜</el-radio-button>
                  </el-radio-group>
                </div>
                <div class="batch-actions" v-if="selectedScores.length > 0">
                  <el-button-group size="small">
                    <el-button type="success" @click="handleBatchApprove">
                      <el-icon><Select /></el-icon> 批量审核
                    </el-button>
                    <el-button type="primary" @click="handleBatchPublish">
                      <el-icon><View /></el-icon> 批量公示
                    </el-button>
                    <el-button type="danger" @click="handleBatchReject">
                      <el-icon><Close /></el-icon> 批量驳回
                    </el-button>
                    <el-button type="warning" @click="handleBatchCertificate">
                      <el-icon><Document /></el-icon> 生成证书
                    </el-button>
                  </el-button-group>
                </div>
              </div>
            </template>

            <!-- 加载状态 -->
            <div v-if="tableLoading" class="table-loading">
              <el-skeleton :rows="5" animated />
            </div>

            <!-- 表格视图 -->
            <div v-else-if="displayMode === 'table'" class="table-view">
              <el-tabs v-model="activeTab" @tab-click="handleTabClick">
                <el-tab-pane label="待审核" name="pending">
                  <EnhancedScoreTable
                    :data="pendingScores"
                    :loading="pendingLoading"
                    :selected-scores="selectedScores"
                    @selection-change="handleSelectionChange"
                    @approve="handleApprove"
                    @reject="handleReject"
                    @publish="handlePublish"
                    @view-detail="handleViewDetail"
                    @view-ranking="handleViewRanking"
                    @generate-certificate="handleGenerateCertificate"
                    @share="handleShare"
                  />
                </el-tab-pane>
                <el-tab-pane label="已公示" name="published">
                  <EnhancedScoreTable
                    :data="publishedScores"
                    :loading="publishedLoading"
                    :selected-scores="selectedScores"
                    @selection-change="handleSelectionChange"
                    @view-detail="handleViewDetail"
                    @view-ranking="handleViewRanking"
                    @generate-certificate="handleGenerateCertificate"
                    @share="handleShare"
                  />
                </el-tab-pane>
                <el-tab-pane label="已驳回" name="rejected">
                  <EnhancedScoreTable
                    :data="rejectedScores"
                    :loading="rejectedLoading"
                    :selected-scores="selectedScores"
                    @selection-change="handleSelectionChange"
                    @view-detail="handleViewDetail"
                    @view-ranking="handleViewRanking"
                  />
                </el-tab-pane>
                <el-tab-pane label="有异议" name="disputed">
                  <EnhancedScoreTable
                    :data="disputedScores"
                    :loading="disputedLoading"
                    :selected-scores="selectedScores"
                    @selection-change="handleSelectionChange"
                    @approve="handleApprove"
                    @reject="handleReject"
                    @publish="handlePublish"
                    @view-detail="handleViewDetail"
                    @view-ranking="handleViewRanking"
                  />
                </el-tab-pane>
              </el-tabs>
            </div>

            <!-- 卡片视图 -->
            <div v-else-if="displayMode === 'card'" class="card-view">
              <ScoreCardView
                :data="getCurrentTabData()"
                :loading="getCurrentTabLoading()"
                @view-detail="handleViewDetail"
                @generate-certificate="handleGenerateCertificate"
                @share="handleShare"
              />
            </div>

            <!-- 排行榜视图 -->
            <div v-else-if="displayMode === 'ranking'" class="ranking-view">
              <ScoreRankingView
                :project-id="selectedProject"
                :loading="rankingLoading"
                @view-detail="handleViewDetail"
                @generate-certificate="handleGenerateCertificate"
                @share="handleShare"
              />
            </div>

            <!-- 分页控制 -->
            <div class="pagination-container">
              <el-pagination
                v-model:current-page="pagination.currentPage"
                v-model:page-size="pagination.pageSize"
                :page-sizes="[10, 20, 50, 100]"
                :total="pagination.total"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </div>

            <!-- 选中项提示 -->
            <div class="selection-info" v-if="selectedScores.length > 0">
              <el-alert
                :title="`已选择 ${selectedScores.length} 项`"
                type="info"
                :closable="false"
                show-icon
              >
                <template #default>
                  <el-button type="text" @click="clearSelection">清空选择</el-button>
                </template>
              </el-alert>
            </div>
          </el-card>
        </div>
      </div>
    </main>

    <!-- 成绩详情对话框 -->
    <ScoreDetailDialog
      v-model="detailDialogVisible"
      :score="selectedScore"
      @close="handleDetailClose"
      @generate-certificate="handleGenerateCertificate"
      @share="handleShare"
    />

    <!-- 成绩排名对话框 -->
    <ScoreRankingDialog
      v-model="rankingDialogVisible"
      :project-id="selectedProjectId"
      :project-name="selectedProjectName"
      @close="handleRankingClose"
    />

    <!-- 审核对话框 -->
    <AuditDialog
      v-model="auditDialogVisible"
      :audit-type="auditType"
      :scores="selectedScores"
      @confirm="handleAuditConfirm"
      @close="handleAuditClose"
    />

    <!-- 证书生成对话框 -->
    <CertificateDialog
      v-model="certificateDialogVisible"
      :scores="certificateScores"
      @close="handleCertificateClose"
    />

    <!-- 分享对话框 -->
    <ShareDialog
      v-model="shareDialogVisible"
      :score="shareScore"
      @close="handleShareClose"
    />

    <!-- 打印预览对话框 -->
    <PrintPreviewDialog
      v-model="printPreviewVisible"
      :scores="getCurrentTabData()"
      @print="handlePrintConfirm"
      @close="handlePrintPreviewClose"
    />
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onUnmounted, nextTick, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Trophy, Odometer, User, List, Clock, SwitchButton,
  Refresh, Download, Printer, Search, Select, View,
  Close, Document, Medal, CreditCard
} from '@element-plus/icons-vue'
import * as echarts from 'echarts'

import {
  getScorePage,
  getScoreStatistics,
  exportScores,
  getPersonalScores,
  batchAuditScores,
  batchPublishScores,
  batchRejectScores
} from '@/api/score'
import { getProjectPage } from '@/api/project'
import EnhancedScoreTable from './components/EnhancedScoreTable.vue'
import ScoreCardView from './components/ScoreCardView.vue'
import ScoreRankingView from './components/ScoreRankingView.vue'
import ScoreDetailDialog from './components/ScoreDetailDialog.vue'
import ScoreRankingDialog from './components/ScoreRankingDialog.vue'
import AuditDialog from './components/AuditDialog.vue'
import CertificateDialog from './components/CertificateDialog.vue'
import ShareDialog from './components/ShareDialog.vue'
import PrintPreviewDialog from './components/PrintPreviewDialog.vue'

// 组件名称
defineOptions({
  name: 'ScoreDisplay'
})

// 当前用户信息
const currentUser = ref(null)

// 活动标签页
const activeTab = ref('pending')

// 显示模式
const displayMode = ref('table')

// 图表类型
const chartType = ref('bar')

// 图表项目ID
const chartProjectId = ref(null)

// 刷新状态
const refreshing = ref(false)

// 图表引用
const departmentChartRef = ref(null)
const projectChartRef = ref(null)

// 图表实例
let departmentChart = null
let projectChart = null

// 统计数据卡片
const statisticsCards = computed(() => ({
  pending: {
    icon: 'Clock',
    value: statistics.value.pending,
    label: '待审核'
  },
  published: {
    icon: 'View',
    value: statistics.value.published,
    label: '已公示'
  },
  rejected: {
    icon: 'Close',
    value: statistics.value.rejected,
    label: '已驳回'
  },
  disputed: {
    icon: 'Document',
    value: statistics.value.disputed,
    label: '有异议'
  }
}))

// 统计数据
const statistics = reactive({
  pending: 0,
  published: 0,
  rejected: 0,
  disputed: 0,
  total: 0,
  recordBreaking: 0
})

// 奖牌统计
const medalStatistics = reactive({
  gold: 0,
  silver: 0,
  bronze: 0
})

// 选中的项目
const selectedProject = ref(null)

// 选项数据
const projectOptions = ref([])
const departmentOptions = ref([
  '计算机学院',
  '电子信息学院',
  '机械工程学院',
  '材料科学与工程学院',
  '自动化学院',
  '管理学院',
  '外国语学院',
  '理学院',
  '艺术学院',
  '体育学院'
])
const statusOptions = ref([
  { label: '待审核', value: 'PENDING' },
  { label: '已公示', value: 'PUBLISHED' },
  { label: '已驳回', value: 'REJECTED' },
  { label: '有异议', value: 'DISPUTED' }
])
const roundOptions = ref([
  { value: 1, label: '第1轮' },
  { value: 2, label: '第2轮' },
  { value: 3, label: '第3轮' },
  { value: 4, label: '决赛' }
])

// 搜索表单
const searchForm = reactive({
  projectId: null,
  studentName: '',
  studentNumber: '',
  department: '',
  status: '',
  round: null,
  isRecord: false
})

// 个人成绩查询表单
const personalForm = reactive({
  studentName: '',
  studentNumber: ''
})

// 各状态成绩数据
const pendingScores = ref([])
const publishedScores = ref([])
const rejectedScores = ref([])
const disputedScores = ref([])

// 加载状态
const searchLoading = ref(false)
const personalLoading = ref(false)
const pendingLoading = ref(false)
const publishedLoading = ref(false)
const rejectedLoading = ref(false)
const disputedLoading = ref(false)
const tableLoading = ref(false)
const rankingLoading = ref(false)

// 选中的成绩
const selectedScores = ref([])

// 分页信息
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 对话框状态
const detailDialogVisible = ref(false)
const rankingDialogVisible = ref(false)
const auditDialogVisible = ref(false)
const certificateDialogVisible = ref(false)
const shareDialogVisible = ref(false)
const printPreviewVisible = ref(false)

// 选中的成绩和项目
const selectedScore = ref(null)
const selectedProjectId = ref(null)
const selectedProjectName = ref(null)

// 审核类型
const auditType = ref('approve')

// 证书成绩
const certificateScores = ref([])

// 分享成绩
const shareScore = ref(null)

// 获取当前标签页数据
const getCurrentTabData = () => {
  const dataMap = {
    pending: pendingScores.value,
    published: publishedScores.value,
    rejected: rejectedScores.value,
    disputed: disputedScores.value
  }
  return dataMap[activeTab.value] || []
}

// 获取当前标签页加载状态
const getCurrentTabLoading = () => {
  const loadingMap = {
    pending: pendingLoading.value,
    published: publishedLoading.value,
    rejected: rejectedLoading.value,
    disputed: disputedLoading.value
  }
  return loadingMap[activeTab.value] || false
}

// 初始化数据
const initData = async () => {
  refreshing.value = true
  try {
    await Promise.all([
      loadProjectOptions(),
      loadStatistics(),
      loadMedalStatistics()
    ])
    loadTableData()
    initCharts()
  } catch (error) {
    console.error('初始化数据失败:', error)
    ElMessage.error('初始化数据失败')
  } finally {
    refreshing.value = false
  }
}

// 加载项目选项
const loadProjectOptions = async () => {
  try {
    const response = await getProjectPage(1, 1000, {})
    if (response.code === 200) {
      projectOptions.value = response.data.records || []
      if (projectOptions.value.length > 0 && !chartProjectId.value) {
        chartProjectId.value = projectOptions.value[0].id
      }
    }
  } catch (error) {
    console.error('获取项目列表失败:', error)
  }
}

// 加载统计数据
const loadStatistics = async () => {
  try {
    const response = await getScoreStatistics()
    if (response.code === 200) {
      Object.assign(statistics, response.data || {})
    }
  } catch (error) {
    console.error('获取统计数据失败:', error)
  }
}

// 加载奖牌统计
const loadMedalStatistics = async (projectId = null) => {
  try {
    const response = await getScoreStatistics(projectId)
    if (response.code === 200) {
      Object.assign(medalStatistics, {
        gold: response.data.gold || 0,
        silver: response.data.silver || 0,
        bronze: response.data.bronze || 0
      })
    }
  } catch (error) {
    console.error('获取奖牌统计失败:', error)
  }
}

// 加载表格数据
const loadTableData = async () => {
  const loadingMap = {
    pending: pendingLoading,
    published: publishedLoading,
    rejected: rejectedLoading,
    disputed: disputedLoading
  }

  const currentLoading = loadingMap[activeTab.value]

  if (currentLoading) return

  currentLoading.value = true
  tableLoading.value = true

  try {
    const statusMap = {
      pending: 'PENDING',
      published: 'PUBLISHED',
      rejected: 'REJECTED',
      disputed: 'DISPUTED'
    }

    const params = {
      ...searchForm,
      status: statusMap[activeTab.value],
      page: pagination.currentPage,
      size: pagination.pageSize
    }

    const response = await getScorePage(pagination.currentPage, pagination.pageSize, params)

    if (response.code === 200) {
      const dataMap = {
        pending: pendingScores,
        published: publishedScores,
        rejected: rejectedScores,
        disputed: disputedScores
      }

      dataMap[activeTab.value].value = response.data.records || []
      pagination.total = response.data.total || 0
    } else {
      ElMessage.error(response.message || '获取数据失败')
    }
  } catch (error) {
    console.error('获取成绩数据失败:', error)
    ElMessage.error('获取数据失败')
  } finally {
    currentLoading.value = false
    tableLoading.value = false
  }
}

// 初始化图表
const initCharts = async () => {
  await nextTick()

  if (departmentChartRef.value) {
    departmentChart = echarts.init(departmentChartRef.value)
    updateDepartmentChart()
  }

  if (projectChartRef.value) {
    projectChart = echarts.init(projectChartRef.value)
    updateProjectChart()
  }

  // 监听窗口大小变化
  window.addEventListener('resize', handleResize)
}

// 更新院系成绩分布图表
const updateDepartmentChart = () => {
  if (!departmentChart) return

  // 模拟数据
  const data = [
    { name: '计算机学院', value: 45 },
    { name: '电子信息学院', value: 38 },
    { name: '机械工程学院', value: 32 },
    { name: '管理学院', value: 28 },
    { name: '自动化学院', value: 25 }
  ]

  const option = {
    title: {
      text: '院系成绩分布',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      bottom: 10,
      left: 'center'
    },
    series: [
      {
        name: '成绩数量',
        type: chartType.value === 'pie' ? 'pie' : 'bar',
        radius: chartType.value === 'pie' ? '50%' : undefined,
        data: chartType.value === 'pie' ? data : data.map(item => item.value),
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ],
    xAxis: chartType.value === 'bar' ? {
      type: 'category',
      data: data.map(item => item.name)
    } : undefined,
    yAxis: chartType.value === 'bar' ? {
      type: 'value'
    } : undefined
  }

  departmentChart.setOption(option)
}

// 更新项目成绩趋势图表
const updateProjectChart = () => {
  if (!projectChart || !chartProjectId.value) return

  // 模拟数据
  const data = [15, 22, 18, 25, 30, 28, 35]

  const option = {
    title: {
      text: '项目成绩趋势',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: ['第1天', '第2天', '第3天', '第4天', '第5天', '第6天', '第7天']
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '成绩数量',
        type: 'line',
        data: data,
        smooth: true,
        areaStyle: {
          opacity: 0.3
        }
      }
    ]
  }

  projectChart.setOption(option)
}

// 监听窗口大小变化
const handleResize = () => {
  departmentChart?.resize()
  projectChart?.resize()
}

// 监听图表类型变化
watch(chartType, () => {
  updateDepartmentChart()
})

// 监听项目变化
watch(chartProjectId, () => {
  updateProjectChart()
})

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1
  loadTableData()
}

// 重置搜索
const handleResetSearch = () => {
  Object.assign(searchForm, {
    projectId: null,
    studentName: '',
    studentNumber: '',
    department: '',
    status: '',
    round: null,
    isRecord: false
  })
  handleSearch()
}

// 个人成绩搜索
const handlePersonalSearch = async () => {
  if (!personalForm.studentName && !personalForm.studentNumber) {
    ElMessage.warning('请输入学生姓名或学号')
    return
  }

  personalLoading.value = true
  try {
    const params = {
      studentName: personalForm.studentName,
      studentNumber: personalForm.studentNumber
    }

    const response = await getPersonalScores(params)
    if (response.code === 200) {
      // 切换到已公示标签页显示个人成绩
      activeTab.value = 'published'
      publishedScores.value = response.data || []
      ElMessage.success('查询成功')
    } else {
      ElMessage.error(response.message || '查询失败')
    }
  } catch (error) {
    console.error('查询个人成绩失败:', error)
    ElMessage.error('查询失败')
  } finally {
    personalLoading.value = false
  }
}

// 刷新数据
const handleRefresh = () => {
  initData()
}

// 导出成绩
const handleExport = () => {
  ElMessageBox.confirm('确定要导出成绩数据吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'info'
  }).then(async () => {
    try {
      const params = {
        ...searchForm,
        status: activeTab.value === 'pending' ? 'PENDING' :
                activeTab.value === 'published' ? 'PUBLISHED' :
                activeTab.value === 'rejected' ? 'REJECTED' : 'DISPUTED'
      }

      const response = await exportScores(params)
      // 创建下载链接
      const url = window.URL.createObjectURL(new Blob([response]))
      const link = document.createElement('a')
      link.href = url
      link.setAttribute('download', `成绩数据_${new Date().toLocaleDateString()}.xlsx`)
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      window.URL.revokeObjectURL(url)

      ElMessage.success('导出成功')
    } catch (error) {
      console.error('导出失败:', error)
      ElMessage.error('导出失败')
    }
  })
}

// 打印成绩
const handlePrint = () => {
  printPreviewVisible.value = true
}

// 打印确认
const handlePrintConfirm = () => {
  window.print()
  printPreviewVisible.value = false
}

// 打印预览关闭
const handlePrintPreviewClose = () => {
  printPreviewVisible.value = false
}

// 项目改变
const handleProjectChange = (projectId) => {
  loadMedalStatistics(projectId)
}

// 奖牌点击
const handleMedalClick = (medalType) => {
  // 设置搜索条件为对应的奖牌类型
  searchForm.rank = medalType === 'gold' ? 1 : medalType === 'silver' ? 2 : 3
  handleSearch()
}

// 标签页切换
const handleTabClick = (tab) => {
  activeTab.value = tab.name
  selectedScores.value = []
  loadTableData()
}

// 表格选择改变
const handleSelectionChange = (selection) => {
  selectedScores.value = selection
}

// 清空选择
const clearSelection = () => {
  selectedScores.value = []
}

// 分页大小改变
const handleSizeChange = (size) => {
  pagination.pageSize = size
  loadTableData()
}

// 当前页改变
const handleCurrentChange = (page) => {
  pagination.currentPage = page
  loadTableData()
}

// 单个审核
const handleApprove = (score) => {
  auditType.value = 'approve'
  selectedScores.value = [score]
  auditDialogVisible.value = true
}

// 单个驳回
const handleReject = (score) => {
  auditType.value = 'reject'
  selectedScores.value = [score]
  auditDialogVisible.value = true
}

// 单个公示
const handlePublish = (score) => {
  auditType.value = 'publish'
  selectedScores.value = [score]
  auditDialogVisible.value = true
}

// 批量审核
const handleBatchApprove = () => {
  auditType.value = 'approve'
  auditDialogVisible.value = true
}

// 批量公示
const handleBatchPublish = () => {
  auditType.value = 'publish'
  auditDialogVisible.value = true
}

// 批量驳回
const handleBatchReject = () => {
  auditType.value = 'reject'
  auditDialogVisible.value = true
}

// 批量生成证书
const handleBatchCertificate = () => {
  certificateScores.value = [...selectedScores.value]
  certificateDialogVisible.value = true
}

// 审核确认
const handleAuditConfirm = async (formData) => {
  const { type, remark } = formData
  const actionMap = {
    approve: batchAuditScores,
    publish: batchPublishScores,
    reject: batchRejectScores
  }

  const actionText = {
    approve: '审核',
    publish: '公示',
    reject: '驳回'
  }

  try {
    const action = actionMap[type]
    const scoreIds = selectedScores.value.map(s => s.id)

    const response = await action({
      scoreIds,
      remark
    })

    if (response.code === 200) {
      ElMessage.success(`${actionText[type]}成功`)
      auditDialogVisible.value = false
      selectedScores.value = []
      loadTableData()
      loadStatistics()
    } else {
      ElMessage.error(response.message || `${actionText[type]}失败`)
    }
  } catch (error) {
    console.error(`${actionText[type]}失败:`, error)
    ElMessage.error(`${actionText[type]}失败`)
  }
}

// 审核对话框关闭
const handleAuditClose = () => {
  auditDialogVisible.value = false
}

// 查看详情
const handleViewDetail = (score) => {
  selectedScore.value = score
  detailDialogVisible.value = true
}

// 详情对话框关闭
const handleDetailClose = () => {
  detailDialogVisible.value = false
  selectedScore.value = null
}

// 查看排名
const handleViewRanking = (score) => {
  selectedProjectId.value = score.projectId
  selectedProjectName.value = score.project?.name
  rankingDialogVisible.value = true
}

// 排名对话框关闭
const handleRankingClose = () => {
  rankingDialogVisible.value = false
  selectedProjectId.value = null
  selectedProjectName.value = null
}

// 生成证书
const handleGenerateCertificate = (score) => {
  certificateScores.value = Array.isArray(score) ? score : [score]
  certificateDialogVisible.value = true
}

// 证书对话框关闭
const handleCertificateClose = () => {
  certificateDialogVisible.value = false
  certificateScores.value = []
}

// 分享成绩
const handleShare = (score) => {
  shareScore.value = score
  shareDialogVisible.value = true
}

// 分享对话框关闭
const handleShareClose = () => {
  shareDialogVisible.value = false
  shareScore.value = null
}

// 退出登录
const handleLogout = () => {
  ElMessageBox.confirm('确定要退出登录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 清除用户信息
    localStorage.removeItem('user')
    localStorage.removeItem('token')
    // 跳转到登录页
    window.location.href = '/login'
  })
}

// 组件挂载
onMounted(() => {
  // 获取当前用户信息
  const userStr = localStorage.getItem('user')
  if (userStr) {
    try {
      currentUser.value = JSON.parse(userStr)
    } catch (error) {
      console.error('解析用户信息失败:', error)
    }
  }

  // 初始化数据
  initData()
})

// 组件卸载
onUnmounted(() => {
  // 销毁图表实例
  departmentChart?.dispose()
  projectChart?.dispose()

  // 移除事件监听
  window.removeEventListener('resize', handleResize)
})
</script>

<style scoped>
/* 基础样式 */
* {
  font-family: 'PingFang SC', -apple-system, BlinkMacSystemFont, sans-serif;
  box-sizing: border-box;
}

body {
  background-color: #f0f2f5;
  color: #1a1a1a;
  margin: 0;
}

/* 容器布局 */
.app-container {
  max-width: 1440px;
  margin: 0 auto;
  display: grid;
  grid-template-columns: 240px 1fr;
  grid-template-rows: 64px 1fr;
  min-height: 100vh;
  background-color: #F5F7FA;
}

/* 顶部导航栏 */
.header {
  grid-column: 1 / -1;
  background: linear-gradient(135deg, #2C5AA0, #1e3d72);
  display: flex;
  align-items: center;
  padding: 0 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  position: sticky;
  top: 0;
  z-index: 1000;
}

.logo {
  font-size: 18px;
  font-weight: bold;
  color: white;
  display: flex;
  align-items: center;
  gap: 8px;
}

.logo .el-icon {
  font-size: 24px;
}

.flex-grow {
  flex-grow: 1;
}

.flex {
  display: flex;
}

.items-center {
  align-items: center;
}

.gap-6 {
  gap: 24px;
}

.gap-2 {
  gap: 8px;
}

/* 左侧导航栏 */
.sidebar {
  background-color: white;
  padding: 16px 0;
  border-right: 1px solid #e4e7ed;
  box-shadow: 2px 0 8px rgba(0, 0, 0, 0.05);
}

.menu-item {
  padding: 12px 24px;
  color: #555;
  display: flex;
  align-items: center;
  gap: 12px;
  transition: all 0.3s ease;
  cursor: pointer;
  position: relative;
}

.menu-item.active,
.menu-item:hover {
  background-color: #e8eff9;
  color: #2C5AA0;
}

.menu-item.active::after {
  content: '';
  position: absolute;
  right: 0;
  top: 0;
  bottom: 0;
  width: 3px;
  background-color: #2C5AA0;
}

.menu-item .el-icon {
  font-size: 18px;
}

/* 主内容区 */
.content {
  padding: 24px;
  display: grid;
  grid-template-rows: auto 1fr;
  gap: 24px;
  overflow-y: auto;
  min-height: calc(100vh - 64px);
}

/* 面包屑导航 */
.breadcrumb {
  margin-bottom: 16px;
}

.main-content-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 16px;
  border-bottom: 1px solid #e4e7ed;
  background-color: white;
  padding: 16px 24px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.header-actions {
  display: flex;
  gap: 12px;
}

/* 统计卡片 */
.statistics-cards {
  margin-bottom: 24px;
}

.stat-card {
  transition: all 0.3s ease;
  border-radius: 12px;
  overflow: hidden;
  border: none;
}

.stat-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
}

.stat-content {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 8px;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  color: white;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.stat-icon.pending {
  background: linear-gradient(135deg, #f39c12, #e67e22);
}

.stat-icon.published {
  background: linear-gradient(135deg, #27ae60, #2ecc71);
}

.stat-icon.rejected {
  background: linear-gradient(135deg, #e74c3c, #c0392b);
}

.stat-icon.disputed {
  background: linear-gradient(135deg, #8e44ad, #9b59b6);
}

.stat-info {
  flex: 1;
}

.stat-value {
  font-size: 32px;
  font-weight: bold;
  color: #2c3e50;
  line-height: 1;
}

.stat-label {
  font-size: 14px;
  color: #7f8c8d;
  margin-top: 4px;
}

/* 奖牌统计 */
.medal-statistics {
  margin-bottom: 24px;
}

.medal-card {
  background: linear-gradient(135deg, #ffffff, #f8f9fa);
  border-radius: 12px;
  border: none;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.medal-content {
  display: flex;
  justify-content: space-around;
  align-items: center;
  padding: 20px 0;
}

.medal-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
  transition: all 0.3s ease;
  cursor: pointer;
  padding: 16px;
  border-radius: 12px;
}

.medal-item:hover {
  transform: scale(1.05);
  background-color: rgba(0, 0, 0, 0.02);
}

.medal-icon {
  font-size: 48px;
  transition: transform 0.3s ease;
}

.medal-item.gold .medal-icon {
  color: #ffd700;
  text-shadow: 0 2px 4px rgba(255, 215, 0, 0.3);
}

.medal-item.silver .medal-icon {
  color: #c0c0c0;
  text-shadow: 0 2px 4px rgba(192, 192, 192, 0.3);
}

.medal-item.bronze .medal-icon {
  color: #cd7f32;
  text-shadow: 0 2px 4px rgba(205, 127, 50, 0.3);
}

.medal-count {
  font-size: 28px;
  font-weight: bold;
  color: #2c3e50;
}

.medal-label {
  font-size: 16px;
  color: #7f8c8d;
}

/* 数据可视化图表 */
.charts-section {
  margin-bottom: 24px;
}

.chart-card {
  border-radius: 12px;
  border: none;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  height: 400px;
}

.chart-container {
  width: 100%;
  height: 320px;
}

/* 主要内容区域 */
.main-content {
  display: grid;
  grid-template-columns: 300px 1fr;
  gap: 24px;
}

/* 左侧面板 */
.left-panel {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.search-card,
.personal-card {
  height: fit-content;
  border-radius: 12px;
  border: none;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 500;
  font-size: 16px;
  color: #2c3e50;
}

/* 右侧面板 */
.right-panel {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.table-card {
  height: fit-content;
  border-radius: 12px;
  border: none;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.header-left {
  display: flex;
  align-items: center;
  gap: 16px;
  flex: 1;
}

.display-mode-group {
  margin-left: 16px;
}

.batch-actions {
  display: flex;
  gap: 12px;
}

/* 表格加载状态 */
.table-loading {
  padding: 20px;
}

/* 表格视图 */
.table-view {
  min-height: 400px;
}

/* 卡片视图 */
.card-view {
  padding: 16px 0;
}

/* 排行榜视图 */
.ranking-view {
  padding: 16px 0;
}

/* 分页容器 */
.pagination-container {
  margin-top: 20px;
  text-align: right;
  padding-top: 16px;
  border-top: 1px solid #e4e7ed;
}

/* 选中项提示 */
.selection-info {
  margin-top: 16px;
}

/* 头像和退出登录 */
#img-head {
  height: 40px;
  width: 40px;
  border-radius: 50px;
}

.denglu {
  color: white;
  font-size: 15px;
  text-decoration: none;
}

.denglu:hover {
  color: #F44346;
}

.text-sm {
  font-size: 14px;
}

.text-white {
  color: white;
}

/* 标签页样式 */
.el-tabs {
  margin-top: 16px;
}

.el-tabs__header {
  margin-bottom: 16px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .main-content {
    grid-template-columns: 1fr;
  }

  .left-panel {
    order: 2;
  }

  .right-panel {
    order: 1;
  }
}

@media (max-width: 768px) {
  .app-container {
    grid-template-columns: 1fr;
  }

  .sidebar {
    display: none;
  }

  .main-content {
    grid-template-columns: 1fr;
  }

  .statistics-cards .el-col {
    margin-bottom: 16px;
  }

  .medal-content {
    flex-direction: column;
    gap: 16px;
  }

  .charts-section .el-col {
    margin-bottom: 16px;
  }

  .main-content-header {
    flex-direction: column;
    gap: 16px;
    align-items: flex-start;
  }

  .header-left {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
}

@media print {
  /* 打印样式 */
  .header,
  .sidebar,
  .header-actions,
  .pagination-container,
  .selection-info,
  .batch-actions {
    display: none !important;
  }

  .content {
    padding: 0;
  }

  .app-container {
    max-width: none;
    grid-template-columns: 1fr;
  }

  .el-card {
    box-shadow: none;
    border: 1px solid #e4e7ed;
  }
}

/* 动画效果 */
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes slideIn {
  from {
    opacity: 0;
    transform: translateX(-20px);
  }
  to {
    opacity: 1;
    transform: translateX(0);
  }
}

@keyframes pulse {
  0% {
    box-shadow: 0 0 0 0 rgba(44, 90, 160, 0.4);
  }
  70% {
    box-shadow: 0 0 0 10px rgba(44, 90, 160, 0);
  }
  100% {
    box-shadow: 0 0 0 0 rgba(44, 90, 160, 0);
  }
}

.stat-card,
.medal-card,
.search-card,
.personal-card,
.table-card,
.chart-card {
  animation: fadeIn 0.5s ease-out;
}

.menu-item {
  animation: slideIn 0.3s ease-out;
}

.menu-item:hover {
  animation: pulse 1.5s infinite;
}

/* 滚动条样式 */
::-webkit-scrollbar {
  width: 8px;
  height: 8px;
}

::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 4px;
}

::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 4px;
}

::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 暗色主题支持 */
@media (prefers-color-scheme: dark) {
  .app-container {
    background-color: #1a1a1a;
  }

  .content {
    background-color: #1a1a1a;
  }

  .sidebar {
    background-color: #2d2d2d;
    border-right-color: #404040;
  }

  .menu-item {
    color: #e0e0e0;
  }

  .menu-item:hover {
    background-color: #3a3a3a;
    color: #4a9eff;
  }
}
</style>